﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LastoRevival.Website;
using System.Text;
using LastoRevival.Website.Settings;
using LastoRevival.Website.Engine;

public static class ThemeHelper
{

	private static Dictionary<string, Theme> themes;

	public static void InitializeThemes()
	{
		themes = new Dictionary<string, Theme>();

		// pull themes from web.config
		foreach (var theme in WebsiteSettings.GetInstance().RegisteredThemes)
		{
			themes.Add(theme, Theme.Load(theme));
		}
	}

	public static bool IsMobile(this HtmlHelper helper)
	{
		return OverridableViewEngine.IsMobile(helper.ViewContext.HttpContext);
	}

	public static bool IsCurrentThemeDefault(this HtmlHelper helper)
	{
		var themeName = helper.GetCurrentThemeName();

		return themeName == WebsiteSettings.GetInstance().DefaultTheme;
	}

	private static string GetCurrentThemeName(this HtmlHelper helper)
	{
		
		// TODO: allow user to select a mobile theme as well
		var themeName = helper.UserSettings().Theme;

		if (string.IsNullOrEmpty(themeName))
		{
			themeName = WebsiteSettings.GetInstance().DefaultTheme;
		}

		return themeName;
	}

	public static Theme GetCurrentTheme(this HtmlHelper helper)
	{
		var themeName = helper.GetCurrentThemeName();

		return GetTheme(helper, themeName);
	}
	
	private static Theme GetTheme(HtmlHelper helper, string themeName)
	{
		var isMobile = OverridableViewEngine.IsMobile(helper.ViewContext.HttpContext);
		
		// sanity check
		if (themes == null)
		{
			throw new Exception("Themes have not been initialized");
		}

		if (!themes.ContainsKey(themeName))
		{
			throw new Exception(string.Format("Theme does not exist '{0}'", themeName));
		}

		return themes[themeName];
	}

	public static IHtmlString GetAvailableThemesList(this HtmlHelper helper, string id, string name, string value)
	{
		const string openTag = "<select id='{0}' name='{1}'>";
		const string optionTag = "\t<option value='{0}' {1}>{0}</option>";
		const string closeTag = "</select>";

		var html = new StringBuilder();

		html.AppendLine(string.Format(openTag, id, name));

		foreach (var theme in themes.Values)
		{
			var selected = theme.Name == value ? "selected='selected'" : "";
			html.AppendLine(string.Format(optionTag, theme.Name, selected));
		}

		html.Append(closeTag);

		return helper.Raw(html.ToString());
	}

}